<!--
 * @Description: 对账单管理
 * @Author: py
 * @Date: 2024-12-23
-->
<script setup lang="ts" name="account-list">
import type { PlusColumn } from 'plus-pro-components'
import type { VxeGridProps, VxePagerEvents } from 'vxe-table'
import { hasPermi } from '@fl/utils/has-permi'
import { useUserStoreWithOut } from '@fl/store/modules/user'
import { useChargeSettleStoreWithOut } from '@/store/modules/charge-settle'
import { dictListApi, useStatementList } from '@fl/api/charge-settle'
import { SearchTable } from '@fl/components'
import { formatTime } from '@fl/utils'
import { cloneDeep } from 'lodash-es'
import { useRouter } from 'vue-router'

import { useDicts } from './hooks/use-dicts'

const router = useRouter()

const userStore = useUserStoreWithOut()
const enterpriseId = userStore.getOrgInfo?.enterpriseId ?? ''
const enterpriseTypeName = userStore.getOrgInfo?.enterpriseTypeName ?? ''
// 判断是否为设备商
const isEquipSupplier = computed(() => enterpriseTypeName === '设备商(清分业务)')

const { getDictLabel, getDictOptions } = useDicts()

type DictItem = {
    dictType: string
    dictValue: string | number
    dictLabel: string
}

const dictList = ref<DictItem[]>([])
const vendorOptions = computed(() => {
    return dictList.value
        .filter(item => item.dictType === 'charge_vendor_type')
        .map(item => ({
            label: item.dictLabel,
            value: item.dictValue,
        }))
})
const verifyStatusOptions = getDictOptions('oVerifyStatus')

function getDictionaryDatas() {
    dictListApi({
        pageNum: 1,
        pageSize: 99999,
    }).then((res) => {
        dictList.value = res || []
    })
}
getDictionaryDatas()

const initialState = {
    vendorId: isEquipSupplier.value ? enterpriseId : '',
    reconciliationName: '',
    reconciliationRange: null,
    reconciliationStatus: '',
}

const queryState = ref(cloneDeep(initialState))

const queryColumns: PlusColumn[] = [
    {
        colProps: {
            span: 6,
        },
        fieldProps: {
            placeholder: '请输入',
        },
        label: '对账单名称',
        labelWidth: 90,
        prop: 'reconciliationName',
        valueType: 'copy',
    },
    {
        colProps: {
            span: 6,
        },
        fieldProps: {
            placeholder: '请选择',
        },
        label: '合作商名称',
        labelWidth: 90,
        options: vendorOptions,
        prop: 'vendorId',
        valueType: 'select',
    },
    {
        colProps: {
            span: 5,
        },
        fieldProps: {
            placeholder: '请选择',
        },
        label: '对账状态',
        labelWidth: 75,
        options: verifyStatusOptions.value,
        prop: 'reconciliationStatus',
        valueType: 'select',
    },
    {
        colProps: {
            span: 7,
        },
        fieldProps: {
            endPlaceholder: '结束月份',
            format: 'YYYY-MM',
            startPlaceholder: '开始月份',
            type: 'monthrange',
            unlinkPanels: true,
            valueFormat: 'YYYY-MM',
        },
        label: '对账期间',
        labelWidth: 75,
        prop: 'reconciliationRange',
        valueType: 'date-picker',
    },
]

if (isEquipSupplier.value) {
    queryColumns.splice(1, 1)
}

const stateMap = {
    1: 'tag-orange',
    2: 'tag-orange',
    3: 'tag-red',
    4: 'tag-blue',
    5: 'tag-green',
}
function formatDate({ cellValue }) {
    return formatTime(cellValue, 'yyyy-MM')
}
function formatPrice({ cellValue }) {
    if (cellValue === null) {
        return ''
    }

    return cellValue === 0 ? '¥ 0' : `¥ ${Number.parseFloat(cellValue).toFixed(2)}`
}

const gridOptions = reactive<VxeGridProps>({
    align: 'left',
    border: 'inner',
    columnConfig: {
        resizable: false,
    },
    columns: [
        { fixed: 'left', field: 'reconciliationCode', minWidth: 130, title: '对账单号' },
        { field: 'reconciliationName', minWidth: 250, title: '对账单名称' },
        { field: 'reconciliationDate', formatter: formatDate, title: '对账期间', width: 110 },
        { field: 'operatorName', minWidth: 130, title: '运营商名称' },
        { field: 'vendorName', minWidth: 160, title: '合作商名称' },
        { field: 'reconciliationTime', title: '对账完成时间', width: 160 },
        { slots: { default: 'status' }, title: '对账状态', width: 135 },
        { align: 'right', field: 'totalAmount', formatter: formatPrice, title: '实收总金额', width: 120 },
        { align: 'right', field: 'platformServiceFee', formatter: formatPrice, title: '平台技术服务费', width: 135 },
        { align: 'right', field: 'parkingFee', formatter: formatPrice, title: '停车费申诉扣减费', width: 145 },
        { align: 'right', field: 'revenue', formatter: formatPrice, title: '营业额', width: 120 },
        { align: 'right', field: 'commission', formatter: formatPrice, title: '佣金', width: 120 },
        { align: 'right', field: 'dueSettlementAmount', formatter: formatPrice, title: '应结算金额', width: 120 },
        { align: 'right', field: 'actualSettlementAmount', formatter: formatPrice, title: '实际结算金额', width: 120 },
        { align: 'right', field: 'actualInvoiceAmount', formatter: formatPrice, title: '实际开票金额', width: 120 },
        { align: 'right', field: 'settlementDiff', formatter: formatPrice, title: '差异值-结算', width: 120 },
        { align: 'right', field: 'invoiceDiff', formatter: formatPrice, title: '差异值-开票', width: 120 },
        { fixed: 'right', slots: { default: 'operate' }, title: '操作', width: 135 },
    ],
    // headerCellClassName: 'table-header-cell',
    // headerRowClassName: 'bg-white',
    maxHeight: 370,
    rowConfig: {
        isHover: true,
        keyField: 'id',
    },
    showOverflow: false,
})

const tablePage = ref({
    currentPage: 1,
    pageSize: 10,
    total: 0,
})
const tableData = ref([])
type BaseParams = {
    orders: {
        column: string
        asc: boolean
    }[]
    pageNum: number
    pageSize: number
    vendorId: string
    reconciliationName: string
    reconciliationStatus: string
    reconciliationRange?: null | [string, string]
    reconciliationStartDate?: string | null
    reconciliationEndDate?: string | null
}

const params = computed(() => {
    const baseParams: BaseParams = {
        orders: [{
            column: 'reconciliation_time',
            asc: false,
        }],
        ...queryState.value,
        pageNum: tablePage.value.currentPage,
        pageSize: tablePage.value.pageSize,
    }

    const reconciliationRange = queryState.value.reconciliationRange
    if (reconciliationRange) {
        const timeStart = day(reconciliationRange[0]).startOf('month').format('YYYY-MM-DD 00:00:00')
        const timeEnd = day(reconciliationRange[1]).endOf('month').format('YYYY-MM-DD 23:59:59')
        baseParams.reconciliationStartDate = timeStart
        baseParams.reconciliationEndDate = timeEnd
    }
    return baseParams
})

const { data, isLoading, refetch } = useStatementList(params)
watchEffect(() => {
    if (data.value) {
        const { records, total } = data.value
        tablePage.value.total = +total
        tableData.value = cloneDeep(records)
    }
})

function handleSearch() {
    tablePage.value.currentPage = 1
    refetch()
}
function handleReset() {
    queryState.value = cloneDeep(initialState)
    tablePage.value.currentPage = 1
    tablePage.value.pageSize = 10
    refetch()
}

const handlePageChange: VxePagerEvents.PageChange = ({ currentPage, pageSize }) => {
    tablePage.value.currentPage = currentPage
    tablePage.value.pageSize = pageSize
    refetch()
}

const chargeSettleStore = useChargeSettleStoreWithOut()
function toForm(oRaw, type) {
    chargeSettleStore.setStatementInfo(oRaw)
    router.push({
        name: 'account-form',
        query: {
            formType: type,
            id: oRaw.id,
        },
    })
}
</script>

<template>
    <ElCard shadow="never"
            class="mb-20 border-none"
    >
        <PlusForm v-model="queryState"
                  :columns="queryColumns"
                  :row-props="{ gutter: 20 }"
                  label-position="right"
        >
            <template #footer>
                <div class="ml-auto">
                    <ElButton type="primary"
                              @click="handleSearch"
                    >
                        搜索
                    </ElButton>

                    <ElButton @click="handleReset">
                        重置
                    </ElButton>
                </div>
            </template>
        </PlusForm>
    </ElCard>

    <ElCard shadow="never"
            class="border-none"
    >
        <SearchTable v-bind="gridOptions"
                     v-model:pager="tablePage"
                     :loading="isLoading"
                     :data="tableData"
                     @page-change="handlePageChange"
        >
            <template #status="{ row }">
                <span class="status-tag"
                      :class="stateMap[row.reconciliationStatus]"
                >
                    {{ getDictLabel('oVerifyStatus', row.reconciliationStatus) }}
                </span>
            </template>

            <template #operate="{ row }">
                <div class="row-btns">
                    <span v-if="row.reconciliationStatus === 1 && hasPermi('对账单管理-发起')"
                          class="btn-operate"
                          @click="toForm(row, 'launch')"
                    >
                        发起
                    </span>

                    <span v-if="row.reconciliationStatus === 2 && hasPermi('对账单管理-设备商确认')"
                          class="btn-operate"
                          @click="toForm(row, 'vendorConfirm')"
                    >
                        确认
                    </span>

                    <span v-if="row.reconciliationStatus === 3 && hasPermi('对账单管理-异常处理')"
                          class="btn-operate"
                          @click="toForm(row, 'exception')"
                    >
                        异常处理
                    </span>

                    <span v-if="row.reconciliationStatus === 4 && hasPermi('对账单管理-上传发票')"
                          class="btn-operate"
                          @click="toForm(row, 'invoice')"
                    >
                        上传发票
                    </span>

                    <span class="btn-operate"
                          @click="toForm(row, 'detail')"
                    >
                        查看
                    </span>
                </div>
            </template>
        </SearchTable>
    </ElCard>
</template>

<style lang="less" scoped>
@import '../custom.less';
</style>
